package com.idanchuang.support.etcache.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author yjy
 * Created at 2021/3/13 6:25 下午
 */
public class InetUtil {

    /**
     * 获取本机内网ip
     * @return ip
     */
    public static String getLocalIp() {
        // 获得本机的所有网络接口
        try {
            Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
            while (nifs.hasMoreElements()) {
                NetworkInterface nif = nifs.nextElement();
                if (nif.isPointToPoint() || nif.isLoopback()) {
                    continue;
                }
                if (nif.getName().startsWith("docker")) {
                    continue;
                }
                // 获得与该网络接口绑定的 IP 地址，一般只有一个
                Enumeration<InetAddress> addresses = nif.getInetAddresses();

                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    if (addr instanceof Inet4Address) {
                        return addr.getHostAddress();
                    }
                }
            }

            return "127.0.0.1";
        } catch (SocketException e) {
            throw new IllegalStateException(e);
        }
    }

}
